package com.marvels.financial.task.service.impl;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.batch.core.Job;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.marvels.financial.task.dto.BatchJobExecutionDTO;
import com.marvels.financial.task.dto.TimedTaskMonitoreDTO;
import com.marvels.financial.task.service.FinancialTimedTaskMonitoreApi;
import com.marvels.financial.utils.ApplicationContextUtil;
import com.marvels.financial.task.QuartzJobLauncher;
import com.marvels.financial.task.dao.FinancialTimedTaskMonitoreDao;
import com.marvels.common.constants.PageConstant;

@Service
public class FinancialTimedTaskMonitoreImpl implements FinancialTimedTaskMonitoreApi {

	@Autowired
	private FinancialTimedTaskMonitoreDao monitoreDao;

	@Override
	public Page<TimedTaskMonitoreDTO> selectTaskList(TimedTaskMonitoreDTO timedTaskMonitoreDTO) {
		int pageSize = Integer.parseInt(timedTaskMonitoreDTO.getPageSize());
		int pageNum = Integer.parseInt(timedTaskMonitoreDTO.getPageNum());
		if (pageSize < 1) {
			pageSize = PageConstant.PAGESIZE;
		}
		if (pageNum < 1) {
			pageNum = PageConstant.CURRPAGE;
		}
		PageHelper.startPage(pageNum, pageSize);
		Page<TimedTaskMonitoreDTO> list=monitoreDao.selectTaskList();
		if(null !=list && list.size()>0){
			for(TimedTaskMonitoreDTO monitoreDTO:list){
				BatchJobExecutionDTO executionDTO=monitoreDao.selectExecuteInfo(monitoreDTO.getJobInstanceId());
				if(executionDTO!=null){
					monitoreDTO.setEndLastTime(executionDTO.getEndTime());
					monitoreDTO.setStatus(executionDTO.getStatus());
					monitoreDTO.setTriggerLastTime(executionDTO.getStartTime());
				}
			}
		}
		return list;
	}

	@Override
	public void runTimedTaskAgain(TimedTaskMonitoreDTO timedTaskMonitoreDTO) throws Exception {
		String jobCode = timedTaskMonitoreDTO.getJobCode();
		JobDataMap jobDataMap = new JobDataMap();
		Job job = (Job)ApplicationContextUtil.getApplicationContext().getBean(jobCode);
		jobDataMap.put("job", job);
		
		JobDetail jobDetail = JobBuilder.newJob(QuartzJobLauncher.class).usingJobData(jobDataMap).build();
		Trigger trigger = TriggerBuilder.newTrigger().startNow()
				.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).withRepeatCount(0)).build();
		
		SchedulerFactory factory = new StdSchedulerFactory();
		Scheduler scheduler = factory.getScheduler();
		scheduler.start();
		scheduler.scheduleJob(jobDetail, trigger);
	}

}
